package com.example.redis.test;

import com.example.redis.tool.RedisLock;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import sun.nio.ch.ThreadPool;

import java.util.UUID;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author:xuecx
 * @descript:<p> </p>
 * @date:2018/10/12
 */
public class IDGender implements Runnable {
    private static int i = 0;

    public static int add() {
        i = i + 1;
        return i;
    }

    private static JedisPool pool = null;
    private RedisTemplate redisTemplate = null;

    static {
        JedisPoolConfig config = new JedisPoolConfig();
        // 设置最大连接数
        config.setMaxTotal(10000);
        // 设置最大空闲数
        config.setMaxIdle(1000);
        // 设置最大等待时间
        config.setMaxWaitMillis(1000 * 100);
        // 在borrow一个jedis实例时，是否需要验证，若为true，则所有jedis实例均是可用的
        config.setTestOnBorrow(false);
        pool = new JedisPool(config, "192.168.47.128", 6379);
    }

    public IDGender() {

    }

    public IDGender(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    @Override
    public void run() {
        UUID uuid = UUID.randomUUID();
        AtomicInteger atomicInteger=new AtomicInteger();
        while (true) {
            boolean addId1 = RedisLock.lock(pool.getResource(), "addId", uuid.toString(), 100);
            if (addId1) {
                add();
                System.out.println(i);
                boolean addId = RedisLock.unLock(pool.getResource(), "addId", uuid.toString());
                break;
            } else {
                System.out.println("未获取到锁");
            }
        }
    }

    public static void main(String[] args) {
        IDGender idGender = new IDGender();
        //ExecutorService poolExecutor = Executors.newFixedThreadPool(10);

       ThreadPoolExecutor poolExecutor=new ThreadPoolExecutor(10,20,1000, TimeUnit.MILLISECONDS,new ArrayBlockingQueue<Runnable>(20));
        for (int i = 0; i < 20; i++) {
            poolExecutor.submit(idGender);
            System.out.println(poolExecutor.getQueue().size());
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
